<template>
  <view class="order-navigation-container">
    <!-- 顶部导航栏 -->
    <view class="nav-tabs">
      <text 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', activeTab === index ? 'active' : '']"
        @click="switchTab(index)"
      >
        {{ tab }}
      </text>
    </view>

    <!-- 按超市分组显示商品 -->
    <view v-for="(group, storeIndex) in filteredGroups" :key="storeIndex" class="store-group">
      <!-- 超市名称和删除按钮 -->
      <view class="store-header">
        <text class="store-name">超市名称: {{ group.storeName }}</text>
        <button class="delete-store-btn" @click="deleteStoreOrder(storeIndex)">删除订单</button>
      </view>
      
      <!-- 显示下单时间 -->
      <view class="order-time-info">
        <text class="order-time">下单时间: {{ group.orderTime }}</text>
        <text class="order-status">状态: {{ getStatusText(group) }}</text>
      </view>
      
      <!-- 商品列表 -->
      <view v-for="(product, productIndex) in group.products" :key="productIndex" class="product-item">
        <image :src="product.imgUrl" class="product-img"></image>
        <view class="product-details">
          <text class="product-desc">{{ product.name }} {{ product.specification }}</text>
          <text class="product-quantity">数量: {{ product.quantity }}</text>
          <text class="product-price">价格: ￥{{ product.price }}</text>
          <view class="action-buttons">
            <!-- <button 
              class="confirm-btn" 
              @click="confirmReceipt(storeIndex, productIndex)"
              v-if="!product.received && activeTab === 1"
            >
              确认收货
            </button> -->
            <button 
              class="cancel-btn" 
              @click="cancelOrder(storeIndex, productIndex)"
              v-if="activeTab === 1"
            >
              取消订单
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupedProducts: [], // 按超市分组的商品数据
      tabs: ['全部', '进行中', '已完成', '已取消'],
      activeTab: 0, // 默认选中全部
      orderStatus: {} // 存储订单状态
    };
  },
  computed: {
    // 根据当前选中的tab筛选订单
    filteredGroups() {
      return this.groupedProducts.filter(group => {
        if (this.activeTab === 0) return true; // 全部
        
        const groupStatus = this.getGroupStatus(group);
        
        if (this.activeTab === 1) return groupStatus === 'processing'; // 进行中
        if (this.activeTab === 2) return groupStatus === 'completed';  // 已完成
        if (this.activeTab === 3) return groupStatus === 'cancelled'; // 已取消
        
        return true;
      });
    }
  },
  onLoad() {
    this.loadOrderData();
  },
  onShow() {
    this.loadOrderData();
  },
  methods: {
    loadOrderData() {
      // 获取所有订单数据
      const allOrders = uni.getStorageSync('allOrders') || [];
      
      // 按超市名称分组
      const storeGroups = {};
      
      allOrders.forEach(order => {
        if (!storeGroups[order.storeName]) {
          storeGroups[order.storeName] = {
            storeName: order.storeName,
            orderTime: order.orderTime,
            products: []
          };
        }
        storeGroups[order.storeName].products.push(...order.products);
      });
      
      // 转换为数组形式
      this.groupedProducts = Object.values(storeGroups);
    },
    
    // 获取订单组的状态
    getGroupStatus(group) {
      // 如果有取消的商品，则整个订单组视为已取消
      if (group.products.some(p => p.cancelled)) {
        return 'cancelled';
      }
      
      // 如果所有商品都已收货，则视为已完成
      if (group.products.every(p => p.received)) {
        return 'completed';
      }
      
      // 否则视为进行中
      return 'processing';
    },
    
    // 获取状态文本
    getStatusText(group) {
      const status = this.getGroupStatus(group);
      return {
        'processing': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }[status];
    },
    
    // 切换标签页
    switchTab(index) {
      this.activeTab = index;
    },
    
    // 删除整个超市订单
    deleteStoreOrder(storeIndex) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个超市的所有订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取所有订单
            const allOrders = uni.getStorageSync('allOrders') || [];
            
            // 获取要删除的超市名称
            const storeName = this.filteredGroups[storeIndex].storeName;
            
            // 过滤掉要删除的超市订单
            const updatedOrders = allOrders.filter(order => order.storeName !== storeName);
            
            // 保存更新后的订单
            uni.setStorageSync('allOrders', updatedOrders);
            
            // 重新加载数据
            this.loadOrderData();
            
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 确认收货
    confirmReceipt(storeIndex, productIndex) {
      uni.showModal({
        title: '提示',
        content: '确认已收到商品吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取所有订单
            const allOrders = uni.getStorageSync('allOrders') || [];
            
            // 找到对应的订单并标记为已收货
            const storeName = this.filteredGroups[storeIndex].storeName;
            const productId = this.filteredGroups[storeIndex].products[productIndex].id;
            
            const updatedOrders = allOrders.map(order => {
              if (order.storeName === storeName) {
                order.products = order.products.map(p => {
                  if (p.id === productId) {
                    return { ...p, received: true };
                  }
                  return p;
                });
              }
              return order;
            });
            
            // 保存更新后的订单
            uni.setStorageSync('allOrders', updatedOrders);
            
            // 重新加载数据
            this.loadOrderData();
            
            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 取消订单
    cancelOrder(storeIndex, productIndex) {
      uni.showModal({
        title: '提示',
        content: '确定要取消这个订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取所有订单
            const allOrders = uni.getStorageSync('allOrders') || [];
            
            // 找到对应的订单并标记为已取消
            const storeName = this.filteredGroups[storeIndex].storeName;
            const productId = this.filteredGroups[storeIndex].products[productIndex].id;
            
            const updatedOrders = allOrders.map(order => {
              if (order.storeName === storeName) {
                order.products = order.products.map(p => {
                  if (p.id === productId) {
                    return { ...p, cancelled: true };
                  }
                  return p;
                });
              }
              return order;
            });
            
            // 保存更新后的订单
            uni.setStorageSync('allOrders', updatedOrders);
            
            // 重新加载数据
            this.loadOrderData();
            
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
          }
        }
      });
    }
  }
};
</script>

<style>
.order-navigation-container {
  padding: 15px;
  padding-top: 0;
}

/* 导航栏样式 */
.nav-tabs {
  display: flex;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
}

.tab-item.active {
  color: #007AFF;
  font-weight: bold;
  border-bottom: 2px solid #007AFF;
}

/* 原有样式调整 */
.store-group {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.delete-store-btn {
  font-size: 12px;
  padding: 4px 8px;
  background-color: transparent;
  color: #afa8a8;
  border: none;
  border-radius: 4px;
  margin-right: 10px;
}

.order-time-info {
  font-size: 14px;
  color: #888;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
}

.order-status {
  color: #007AFF;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-img {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 15px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-desc {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.product-quantity, .product-price {
  font-size: 14px;
  color: #666;
}

.action-buttons {
  display: flex;
  margin-top: 8px;
}

.confirm-btn {
  font-size: 12px;
  padding: 5px 10px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  margin-right: 5px;
}

.cancel-btn {
  font-size: 12px;
  padding: 5px 10px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  margin-right: 5px;
}
</style>